import { MenuTypeEnum } from '@/api/modules/system/menu/types';
import type { Routers } from '@/api/modules/system/user/types';
import { getRouters } from '@/api/modules/system/user/user';
import { getSystemIcon } from '@/api/utils/image';
import logoPng from '@/assets/logo.png';
import { openBrowser } from '@/global/window/widget';

import { activeWindow, openWindow } from '@/global/window/window';
import { systemComponents } from '@/initialization';
import { openLink } from '@/utils/common/utils';
import FolderVue from '@/views/selector/folder/Folder.vue';
import { message } from 'ant-design-vue';

export const appLoading = ref(false);

export const userRouters = ref<Routers[]>([]);

/**
 * @description: 获取用户路由，多处复用
 */
export const getUserRouters = async () => {
  appLoading.value = true;
  const { data } = await getRouters();
  if (data.data) {
    userRouters.value = data.data;
  }
  appLoading.value = false;
  return data.data || [];
};
/**
 * @description:
 * 多处复用
 * 此处需要优化
 */
export const getIconByName = (item: Routers) => {
  if (item.menuType === MenuTypeEnum.CATEGORY) {
    return getSystemIcon(`system/folder.png`);
  } else if (item.menuType === MenuTypeEnum.LINK) {
    return getSystemIcon(`system/edge.png`);
  } else if (item.menuType === MenuTypeEnum.MENU && item.icon) {
    return getSystemIcon(item.icon);
  }
  return logoPng;
};
/**
 * @description:
 *  核心功能，打开菜单
 * @param {Routers} item
 */
export const openApp = async (item: Routers) => {
  if (item.menuType === MenuTypeEnum.CATEGORY) {
    openWindow({
      component: markRaw(FolderVue),
      title: `${item.title || 'Untitled'}`,
      data: item.children || [],
      id: `${item.id}`,
      icon: getIconByName(item),
      w: 400,
      maximize: false,
    });
    return;
  } else if (item.menuType === MenuTypeEnum.MENU) {
    const isExist = systemComponents.value.find(e => {
      if (item.component && e.path.includes(item.component)) {
        openWindow({
          title: item.title,
          component: e.component,
          id: `${item.id}`,
          icon: getIconByName(item),
          w: item.width,
          h: item.height,
        });
        return e;
      }
      return null;
    });
    if (!isExist) {
      message.warn(`当前版本不支持这个功能`);
      return;
    }
  } else if (item.menuType === MenuTypeEnum.LINK) {
    openLink(item.path);
  } else if (item.menuType === MenuTypeEnum.DYNAMIC) {
    openBrowser({
      src: item.path,
      type: 'link',
    });
  } else {
    message.warn(`当前版本不支持这个功能`);
    return;
  }
  activeWindow(item.name);
};
